﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Tools;
using Ext.Net;
using Itop.GpsCar.Model;
using Itop.GpsCar.Web;
using Itop.GpsCar.BLL;
using System.Data;
using Web;
using System.Collections;
namespace Web.Admin
{
    public partial class Default : System.Web.UI.Page
    {
        
        protected void Page_PreLoad(object sender, EventArgs e)
        {
            if (CookieHelper.GetCookie("username") == null || CookieHelper.GetCookie("role") == null)
                Response.Redirect("Login.aspx");
            if (!IsPostBack)
                ThemeChange();
            if (!X.IsAjaxRequest)
            {
                userBLL mgr = Global.GetService<userBLL>();
                IList<user>  list= mgr.Select();
                DataTable dt = ConvertHelper.ToDataTable(list as IList);
                if (dt.Rows.Count > 0)
                {
                    this.BuildTree(this.TreePanel1.Root, dt);
                }
                else
                {
                    MsgBox.MessageShow("没有取得数据", "ERROR");
                }  
            }
        }
        //登录
        protected void BtnSave_Click(object sender, DirectEventArgs e)
        {
            if (TxtNewPwd.Text.Trim().Length <= 0 || TxtOldPwd.Text.Trim().Length <= 0)
            {
                MsgBox.MessageShow("信息不完整！", "ERROR");
                return;
            }
            if (TxtSurePwd.Text != TxtNewPwd.Text)
            { MsgBox.MessageShow("两次新密码输入不一致！", "ERROR"); return; }
            userBLL mgr=Global.GetService<userBLL>();
            user userinfo = mgr.GetByUsername( CookieHelper.GetCookie("username"));
            //
            if (userinfo != null && userinfo.password.Trim() == this.TxtOldPwd.Text.Trim().Replace("'", ""))
            {
                userinfo.password = this.TxtSurePwd.Text.Trim().Replace("'", "");
                if (mgr.Update(userinfo)==1)
                {
                    MsgBox.MessageShow("密码修改成功，请重新登录系统！", "INFO");
                    Response.Redirect("Login.aspx");
                    return;
                }
                MsgBox.MessageShow("密码修改失败，请重试！", "ERROR");
            }
            else
                MsgBox.MessageShow("旧密码错误，请重新输入！", "ERROR");
        }
        //退出系统
        protected void BtnExit_Click(object sender, DirectEventArgs e)
        {
            CookieHelper.ClearCookie(CookieHelper.GetCookie("username"));
            CookieHelper.ClearCookie("username");
            CookieHelper.ClearCookie("role");
            Response.Redirect("Login.aspx");
        }

        public Ext.Net.TreeNode BindTreePanel(DataTable allData)
        {
          Ext.Net.TreeNode topNode = new Ext.Net.TreeNode();
            topNode.NodeID = "0";
            topNode.Text = "Root";

            if (allData != null && allData.Rows.Count > 0)
            {
                DataRow[] items = allData.Select("puserid='0'");
                if (items != null && items.Length > 0)
                {
                    DataSet ds = new DataSet();
                    ds.Merge(items);
                    DataTable SourseTable = ds.Tables[0];

                    for (int i = 0; i < SourseTable.Rows.Count; i++)
                    {
                        Ext.Net.TreeNode Tvn = new Ext.Net.TreeNode();
                        Tvn.Expandable = ThreeStateBool.True;
                        Tvn.NodeID = SourseTable.Rows[i]["userid"].ToString();
                        Tvn.Text = SourseTable.Rows[i]["username"].ToString();
                        DataRow[] isChildNode = allData.Select("puserid=" + SourseTable.Rows[i]["userid"].ToString());
                        if (isChildNode.Length <= 0)
                        {
                            Tvn.Leaf = true;
                            Tvn.Checked = Ext.Net.ThreeStateBool.False;
                        }
                        if (isChildNode.Length > 0) Tvn.Icon = Icon.FolderGo;
                        else Tvn.Icon = Icon.Table;

                        BindSubTreePanel(Tvn, allData, SourseTable.Rows[i]["userid"].ToString());
                        topNode.Nodes.Add(Tvn);

                    }
                }
            }
            return topNode;
        }
        private void BindSubTreePanel(Ext.Net.TreeNode TrNode, DataTable allData, string parentID)
        {
            DataRow[] items = allData.Select("puserid=" + parentID);

            if (items != null && items.Length > 0)
            {
                DataSet ds = new DataSet();
                ds.Merge(items);
                DataTable dt = ds.Tables[0];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    Ext.Net.TreeNode Tvn = new Ext.Net.TreeNode();
                    Tvn.Icon = Icon.Note;
                    Tvn.NodeID = dt.Rows[i]["userid"].ToString();
                    Tvn.Text = dt.Rows[i]["username"].ToString();
                    DataRow[] isChildNode = allData.Select("puserid=" + dt.Rows[i]["userid"].ToString());
                    if (isChildNode.Length <= 0)
                    {
                        Tvn.Leaf = true;
                        Tvn.Checked = Ext.Net.ThreeStateBool.False;
                    }
                    if (isChildNode.Length > 0) Tvn.Icon = Icon.FolderGo;
                    else Tvn.Icon = Icon.Table;

                    BindSubTreePanel(Tvn, allData, dt.Rows[i]["userid"].ToString());
                    TrNode.Nodes.Add(Tvn);
                }
            }

        }
        private Ext.Net.TreeNodeCollection BuildTree(Ext.Net.TreeNodeCollection root, DataTable dt)
        {
            root.Add(this.BindTreePanel(dt));
            return root;
        }  
        /// <summary>
        /// 获取用户角色功能菜单树
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GetModuNodes(object sender, NodeLoadEventArgs e)
        {
            e.Nodes.Add(new Ext.Net.TreeNode(){ NodeID="1", Href="core/usermgr.aspx", Text="客户管理", Icon= Icon.UserHome});
        }
        
        protected void AddNode2Favorite_Click(object sender, DirectEventArgs e)
        {
            
        }

        //保存皮肤到cookie
        protected void cbTheme_changed(object sender, DirectEventArgs e)
        {
            Response.Cookies["theme"].Value = cbTheme.SelectedItem.Value.ToString();
            Response.Cookies["theme"].Expires = DateTime.Now.AddDays(100d);
            Response.Redirect(Request.Url.ToString());
        }
        /// <summary>
        /// 皮肤切换后保存到cookie中，下次登录加载皮肤
        /// </summary>
        private void ThemeChange()
        {
            if (Request.Cookies["theme"] != null)
            {
                switch (Request.Cookies["theme"].Value)
                {
                    case "gray":
                        HttpContext.Current.Session["Ext.net.Theme"] = Ext.Net.Theme.Gray;
                        cbTheme.SetValue("gray");
                        break;
                    case "access":
                        HttpContext.Current.Session["Ext.net.Theme"] = Ext.Net.Theme.Access;
                        cbTheme.SetValue("access");
                        break;
                    case "slate":
                        HttpContext.Current.Session["Ext.net.Theme"] = Ext.Net.Theme.Slate;
                        cbTheme.SetValue("slate");
                        break;
                    default:
                        HttpContext.Current.Session["Ext.net.Theme"] = Ext.Net.Theme.Default;
                        cbTheme.SetValue("default");
                        break;
                }
            }
            if (CookieHelper.GetCookie("username") != null)
            {
                this.Lbname.Html = "当前用户：" + CookieHelper.GetCookie("username") + "--" + CookieHelper.GetCookie("cn_name");
            }
        }
    }
}